﻿using Microsoft.EntityFrameworkCore;

namespace XsqTech.SmartOA.EFCore.Respository.Base
{
    /// <summary>
    /// 工作单元的实现类
    /// </summary>
    public class UnitOfWork<TDbcontext> : IUnitOfWork where//泛型约束
        TDbcontext : DbContext
    {
        //数据库dbcontext上下文
        readonly DbContext _db;

        public UnitOfWork(DbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 提交事务（非异步）
        /// </summary>
        /// <returns></returns>
        public int SaveChangs()
        {
            int code;
            try
            {
                code = _db.SaveChanges();
            }
            catch (DbUpdateException e)
            {
                //抛出异常
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.Message);
            }
            return code;
        }
        /// <summary>
        /// 异步提交(await/async)
        /// </summary>
        /// <returns></returns>
        public async Task<int> SaveChangsAsync()
        {
            int code;
            try
            {
                code = await _db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
            return code;
        }
    }
}
